﻿using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace ZhukBlogLinqExamples.WebParts.SPStatefulLongOperationWP
{
    [ToolboxItemAttribute(false)]
    public partial class SPStatefulLongOperationWP : WebPart
    {
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling using
        // the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public SPStatefulLongOperationWP()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        private void InitializeControl()
        {
            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SPStatefulLongOperation.Begin(
                "CLOCK",
                "<span id='currentTime'></span>",
                (op) =>
                    {
                        op.Run((opState) =>
                                   {
                                       var currentDate = DateTime.Now;
                                       var endDate = currentDate.AddMinutes(20);
                                       while (endDate > DateTime.Now)
                                       {
                                           opState.Status = string.Format(
                                               "<script type='text/javascript'>document.all.item('currentTime').innerText = '{0}';</script>",
                                               DateTime.Now.ToString("HH:mm:ss"));
                                       }
                                   });
                        op.End(System.Web.HttpContext.Current.Request.UrlReferrer.ToString());
                    });
        }
    }
}
